package org.jetnuke.modules.blog;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.servlets.utilities.StringUtils;
import org.jetnuke.util.JetUtil;

public class GetResource implements IAction {
	String file;
	int uid;
	public void setUid(int uid) {
		this.uid = uid;
	}
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		
		
		String dir=SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/blog/"+uid+"/";
		File f=new File(dir,file);
		if(!f.exists())
			return null;
		
		
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(f));
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		byte[] b = new byte[4096];
		
		while ((bis.read(b)) != -1) {
			baos.write(b);
		}
		bis.close();
		JetUtil.manageReponseCookies(vc,response);
		String mimeType=StringUtils.findMimeType(file);
		
		if(!"?".equals(mimeType)){
			response.setContentType(mimeType);
    		response.setContentLength(baos.size());
			response.setHeader("Expires", "0");
			response.setHeader("Content-disposition","inline" );
    	}else{
    		response.setContentLength(baos.size());
    		response.setContentType("application/octet-stream");
    		response.setHeader("Content-Disposition", "attachment;filename=\"" + file + "\"");
    	}
		
		baos.writeTo(response.getOutputStream());
		return null;
	}
	public void setFile(String file) {
		this.file = file;
	}

}
